package com.example.classassistant;

import javafx.animation.PauseTransition;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Popup;
import javafx.util.StringConverter;


public class MainController {
    @FXML
    private BorderPane MainScene;

    @FXML
    private TextField addClassName;

    @FXML
    private TextField addGroupName;

    @FXML
    private TextField addStudentName;
    @FXML
    private TextField addStudentID;

    @FXML
    private TextField groupScore;

    @FXML
    private TextArea groupView;
    @FXML
    private TextArea studentView;
    @FXML
    private TextArea classView;

    @FXML
    private ComboBox<Class> chooseClass;
    @FXML
    private ComboBox<Group> chooseGroup;
    @FXML
    private ComboBox<Student> chooseStudent;
    private ObservableList<Class> classes = FXCollections.observableArrayList();
    private Class selectedClass;
    private Group selectedGroup;
    private Student selectedStudent;

    public void initialize(){
        displayClass();
        displayGroup();
        displayStudent();
    }
    private Popup popup = new Popup();
    public void popupWarning(String s){
        //警告弹窗，1秒后消失
        Label label = new Label(s);
        VBox vBox = new VBox();
        vBox.getChildren().add(label);
        vBox.setStyle("-fx-background-color: white;");
        vBox.setPrefWidth(200);
        vBox.setPrefHeight(60);
        vBox.setAlignment(Pos.CENTER);
        popup.getContent().clear();
        popup.getContent().add(vBox);
        popup.show(MainScene.getScene().getWindow(),700,350);

        PauseTransition delay = new PauseTransition(javafx.util.Duration.seconds(1));
        delay.setOnFinished(e -> popup.hide());
        delay.play();
    }
    public void displayClass(){
        //打印现有班级
        if (classes == null || classes.isEmpty()) {
            return;
        }
        chooseClass.setItems(classes);
        chooseClass.setConverter(new StringConverter<Class>() {
            @Override
            public String toString(Class clazz) {
                return clazz == null ? "" : clazz.className;
            }
            @Override
            public Class fromString(String string) {
                return null;
            }
        });
        chooseClass.setOnAction(event -> {
            selectedClass = chooseClass.getValue();
        });
    }
    public void displayGroup(){
        //打印现有小组
        if (selectedClass == null|| selectedClass.getGroups() == null || selectedClass.getGroups().isEmpty()) {
            return;
        }
        chooseGroup.setItems(selectedClass.getGroups());
        chooseGroup.setConverter(new StringConverter<Group>() {
            @Override
            public String toString(Group group) {
                return group == null ? "" : group.groupName;
            }
            @Override
            public Group fromString(String string) {
                return null;
            }
        });
        chooseGroup.setOnAction(event -> {
            selectedGroup = chooseGroup.getValue();
        });
    }
    public void displayStudent(){
        //打印现有小组
        if (selectedGroup == null|| selectedGroup.getStudents() == null || selectedGroup.getStudents().isEmpty()) {
            return;
        }
        chooseStudent.setItems(selectedGroup.getStudents());
        chooseStudent.setConverter(new StringConverter<Student>() {
            @Override
            public String toString(Student student) {
                return student == null ? "" : student.name;
            }
            @Override
            public Student fromString(String string) {
                return null;
            }
        });
        chooseStudent.setOnAction(event -> {
            selectedStudent = chooseStudent.getValue();
        });
    }

    @FXML
    public void addClass(ActionEvent event) {
        //添加班级
        String className = addClassName.getText();
        if (className == null || className.trim().isEmpty()) {
            popupWarning("请输入添加的班级名字");
            return;
        }
        Class newClass = new Class(className);
        classes.add(newClass);
        displayClass();
        displayClass();
        displayStudent();
        addClassName.clear();

    }

    @FXML
    public void addGroup(ActionEvent event) {
        //添加小组
        if (selectedClass == null) {
            popupWarning("请选择班级");
            return;
        }
        String groupName = addGroupName.getText();
        if (groupName == null || groupName.trim().isEmpty()) {
            popupWarning("请输入添加的小组名字");
            return;
        }
        Group newGroup = new Group(groupName);
        selectedClass.addGroup(newGroup);

        displayGroup(); // 立即更新小组显示
        displayStudent();
        addGroupName.clear(); // 清空输入框

    }

    @FXML
    public void addStudent(ActionEvent event) {
        //添加学生
        if (selectedClass == null) {
            popupWarning("请选择班级");
            return;
        }
        if (selectedGroup == null) {
            popupWarning("请选择小组");
            return;
        }
        if (addStudentName.getText() == null || addStudentName.getText().trim().isEmpty()) {
            popupWarning("请输入添加的学生名字");
            return;
        }
        if (addStudentID.getText() == null || addStudentID.getText().trim().isEmpty()) {
            popupWarning("请输入添加的学生学号");
            return;
        }

        String studentName = addStudentName.getText();
        int studentId = Integer.parseInt(addStudentID.getText());

        Student newStuent = new Student(studentName, studentId);
        selectedGroup.addStudent(newStuent);

        displayStudent(); // 立即更新小组显示
        addStudentName.clear(); // 清空输入框
        addStudentID.clear();
    }

    @FXML
    public void getStudentFromClass(ActionEvent event) {
        //从班级选学生
        if(selectedClass == null){
            popupWarning("请选择班级");
            return;
        }
        RandomRollCall a = new RandomRollCall(selectedClass);
        int index =  a.pickRandomGroup();
        if(index == -1){
            popupWarning("没有小组");
            return;
        }
        Group group = selectedClass.getGroups().get(index);
        chooseGroup.setValue(group);
        displayGroup();
        index = a.pickRandomStudentFromGroup(group);
        if(index == -1){
            popupWarning("小组中没有学生");
            return;
        }
        Student student = group.getStudents().get(index);
        chooseStudent.setValue(student);
        displayStudent();

    }

    @FXML
    public void getStudentFromGroup(ActionEvent event) {
        //从小组中选择学生
        if(selectedGroup == null){
            popupWarning("请选择小组");
            return;
        }
        RandomRollCall a = new RandomRollCall(selectedClass);
        int index =  a.pickRandomStudentFromGroup(selectedGroup);
        if(index == -1){
            popupWarning("小组中没有学生");
            return;
        }
        Student student = selectedGroup.getStudents().get(index);
        chooseStudent.setValue(student);
        displayStudent();
    }

    @FXML
    public void recordAnswer(ActionEvent event) {
        //记录学生成绩
        if(selectedStudent == null){
            popupWarning("请选择学生");
            return;
        }
        selectedStudent.addCorrectNumber();
    }

    @FXML
    public void recordAttendance(ActionEvent event) {
        //记录考勤
        if(selectedStudent == null){
            popupWarning("请选择学生");
            return;
        }
        selectedStudent.addAttendance();
    }

    @FXML
    public void setGroupSource(ActionEvent event) {
        //设置小组成绩
        if(selectedGroup == null){
            popupWarning("请选择小组");
            return;
        }
        if(groupScore.getText() == null || groupScore.getText().isEmpty()){
            popupWarning("请输入成绩");
            return;
        }
        int score = Integer.parseInt(groupScore.getText());
        selectedGroup.setScore(score);
    }

    @FXML
    public void checkClass(ActionEvent event){
        //查看班级情况
        if(selectedClass == null){
            popupWarning("请选择班级");
            return;
        }
        StringBuilder output = new StringBuilder();
        output.append("Grade: ").append(selectedClass.className).append("\n");
        for (Group group : selectedClass.getGroups()) {
            output.append("Grade: ").append(group.groupName)
                    .append("  小组成绩：").append(group.getScore()).append("\n");
            for (Student student : group.getStudents()) {
                output.append("name：").append(student.name)
                        .append("   id：").append(student.id)
                        .append("   考勤次数：").append(student.getAttendance())
                        .append("   答对次数：").append(student.getCorrectNumber()).append("\n");
            }
            output.append("\n"); // 分隔不同小组的信息
        }

        // 设置 TextArea 的文本
        classView.setText(output.toString());
    }

    @FXML
    public void checkGroup(ActionEvent event) {
        //查看小组情况
        if(selectedGroup == null){
            popupWarning("请选择小组");
            return;
        }
        StringBuilder output = new StringBuilder();
        output.append("Grade: ").append(selectedGroup.groupName)
                .append("  小组成绩：").append(selectedGroup.getScore()).append("\n");
        for (Student student : selectedGroup.getStudents()) {
            output.append("name：").append(student.name)
                    .append("   id：").append(student.id)
                    .append("   考勤次数：").append(student.getAttendance())
                    .append("   答对次数：").append(student.getCorrectNumber()).append("\n");
        }

        // 设置 TextArea 的文本
        groupView.setText(output.toString());
    }

    @FXML
    public void checkStudent(ActionEvent event) {
        //查看学生情况
        if(selectedStudent == null){
            popupWarning("请选择学生");
            return;
        }
        String s = selectedStudent.toString();
        studentView.setText(s);
    }


    @FXML
    public void removeClass(ActionEvent event) {
        if(selectedClass == null){
            popupWarning("请选择要移除的班级");
            return;
        }
        classes.remove(selectedClass);
        popupWarning("移除成功");
        displayClass();
    }
    @FXML
    public void removeGroup(ActionEvent event) {
        if(selectedGroup == null){
            popupWarning("请选择要移除的小组");
            return;
        }
        selectedClass.removeGroup(selectedGroup);
        popupWarning("移除成功");
        displayGroup();
    }

    @FXML
    public void removeStudent(ActionEvent event) {
        if(selectedStudent == null){
            popupWarning("请选择要移除的学生");
            return;
        }
        selectedGroup.removeStudent(selectedStudent);
        popupWarning("移除成功");
        displayStudent();
    }

}
